/*
 * File Name:               DemoColorWindow.cs
 * 
 * Description:             普通类
 * Author:                  lisiyu <576603306@qq.com>
 * Create Date:             2017/03/01
 */


using UnityEngine;
using UnityEngine.UI;

public class DemoColorWindow : UIWindow
{

    private Button mBtnClose;
    private RawImage mImgSB;
    private UITouch mTouchSB;
    private RectTransform mCursorSB;
    private RawImage mImgH;
    private UITouch mTouchH;
    private RectTransform mCursorH;

    protected override void onCacheComponents()
    {
        mBtnClose = getComponent<Button>(0);

        mImgSB = getComponent<RawImage>(1);
        mTouchSB = getComponent<UITouch>(1);
        mCursorSB = getComponent<RectTransform>(2);

        mImgH = getComponent<RawImage>(3);
        mTouchH = getComponent<UITouch>(3);
        mCursorH = getComponent<RectTransform>(4);

        var imgH = ColorExtension.getHTexture2D((int)mImgH.rectTransform.sizeDelta.x, (int)mImgH.rectTransform.sizeDelta.y);
        mImgH.texture = imgH;

        mTextureSB = new Texture2D((int)mImgSB.rectTransform.sizeDelta.x, (int)mImgSB.rectTransform.sizeDelta.y);
        mImgSB.texture = mTextureSB;
    }

    protected override void onClearComponents()
    {

    }

    protected override void onAddListeners()
    {
        mBtnClose.addListener(closeSelf);
        mTouchSB.addListener(onTouchSB);
        mTouchH.addListener(onTouchH);
    }

    protected override void onRemoveListeners()
    {

    }

    private float mHValue;
    private float mSValue;
    private float mBValue;
    private Texture2D mTextureSB;
    protected override void onOpen(object args)
    {
        onTouchSB(Vector2.zero);
        onTouchH(Vector2.zero);

        displayImgSB();
    }

    protected override void onClose()
    {

    }

    private void onTouchSB(Vector2 position)
    {
        mSValue = position.x * 100;
        mBValue = position.y * 100;

        mCursorSB.anchoredPosition = new Vector2(mImgSB.rectTransform.sizeDelta.x * position.x, mImgSB.rectTransform.sizeDelta.y * position.y);
    }

    private void onTouchH(Vector2 position)
    {
        mHValue = position.y * 360;
        displayImgSB();

        mCursorH.anchoredPosition = new Vector2(0, mImgH.rectTransform.sizeDelta.y * position.y);
    }

    private void displayImgSB()
    {
        var colors = mTextureSB.GetPixels();
        float h, s, v;
        h = mHValue;

        for (int i = 0; i < mTextureSB.width; i++)
        {
            s = 1f * i / (mTextureSB.width - 1);
            for (int j = 0; j < mTextureSB.height; j++)
            {
                v = 1f * j / (mTextureSB.height - 1);
                colors[j * mTextureSB.width + i] = Color.HSVToRGB(h, s, v);
            }
        }

        mTextureSB.SetPixels(colors);
        mTextureSB.Apply();
    }
}

